<template>
  <div class="register-container">
    <el-card class="card-container">
      <div slot="header" class="card-header">
        <span>司机人脸注册</span>
      </div>

      <el-form
        ref="registerForm"
        :model="registerForm"
        :rules="rules"
        label-width="120px"
      >
        <!-- 人脸信息部分 -->
        <div class="form-section">
          <h3 class="section-title">人脸信息</h3>

          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="司机姓名" prop="driverName">
                <el-input
                  v-model="registerForm.driverName"
                  placeholder="请输入司机姓名"
                ></el-input>
              </el-form-item>

              <el-form-item label="身份证号" prop="idCard">
                <el-input
                  v-model="registerForm.idCard"
                  placeholder="请输入身份证号"
                ></el-input>
              </el-form-item>

              <el-form-item label="性别">
                <el-radio-group v-model="registerForm.driverSex">
                  <el-radio label="男">男</el-radio>
                  <el-radio label="女">女</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="民族">
                <el-input
                  v-model="registerForm.driverNation"
                  placeholder="请输入民族"
                ></el-input>
              </el-form-item>

              <el-form-item label="出生日期">
                <el-date-picker
                  v-model="registerForm.driverBirth"
                  type="date"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>

              <el-form-item label="住址" prop="driverAddress">
                <el-input
                  v-model="registerForm.driverAddress"
                  type="textarea"
                  placeholder="请输入详细住址"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <div class="face-image-section">
                <el-form-item label="人脸照片">
                  <div class="image-uploader">
                    <el-upload
                      ref="faceUpload"
                      :action="uploadUrl"
                      :before-upload="handleFaceUploadBefore"
                      :on-success="handleFaceUploadSuccess"
                      :on-error="handleFaceUploadError"
                      :auto-upload="false"
                      list-type="picture-card"
                      accept="image/*"
                    >
                      <i slot="default" class="el-icon-plus"></i>
                      <div slot="file" slot-scope="{ file }">
                        <img
                          class="el-upload-list__item-thumbnail"
                          :src="file.url"
                          alt=""
                        />
                        <span class="el-upload-list__item-actions">
                          <span
                            class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview(file)"
                          >
                            <i class="el-icon-zoom-in"></i>
                          </span>
                          <span
                            class="el-upload-list__item-delete"
                            @click="handleRemove(file)"
                          >
                            <i class="el-icon-delete"></i>
                          </span>
                        </span>
                      </div>
                    </el-upload>

                    <el-button
                      type="primary"
                      size="small"
                      class="camera-button"
                      @click="startCamera"
                    >
                      <i class="el-icon-video-camera"></i> 拍摄照片
                    </el-button>
                  </div>

                  <div v-if="isDetecting" class="detection-status">
                    <i class="el-icon-loading"></i> 正在进行人脸检测...
                  </div>

                  <div v-if="detectionResult" class="detection-result">
                    <el-tag
                      :type="detectionResult.success ? 'success' : 'danger'"
                    >
                      {{ detectionResult.message }}
                    </el-tag>
                  </div>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 证件识别部分 -->
        <div class="form-section">
          <h3 class="section-title">证件识别</h3>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="身份证识别">
                <el-upload
                  :action="uploadUrl"
                  :before-upload="handleIdCardUploadBefore"
                  :on-success="handleIdCardUploadSuccess"
                  :on-error="handleIdCardUploadError"
                  :auto-upload="false"
                  list-type="picture-card"
                  accept="image/*"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="idCardPreview"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="
                          handlePictureCardPreview({ url: idCardPreview })
                        "
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        class="el-upload-list__item-delete"
                        @click="clearIdCardImage"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <div class="ocr-tips">上传身份证正面照片自动识别信息</div>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="驾驶证识别">
                <el-upload
                  :action="uploadUrl"
                  :before-upload="handleDrivingLicenseUploadBefore"
                  :on-success="handleDrivingLicenseUploadSuccess"
                  :on-error="handleDrivingLicenseUploadError"
                  :auto-upload="false"
                  list-type="picture-card"
                  accept="image/*"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="drivingLicensePreview"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="
                          handlePictureCardPreview({
                            url: drivingLicensePreview,
                          })
                        "
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        class="el-upload-list__item-delete"
                        @click="clearDrivingLicenseImage"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <div class="ocr-tips">上传驾驶证主页照片自动识别信息</div>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="行驶证识别">
                <el-upload
                  :action="uploadUrl"
                  :before-upload="handleVehicleLicenseUploadBefore"
                  :on-success="handleVehicleLicenseUploadSuccess"
                  :on-error="handleVehicleLicenseUploadError"
                  :auto-upload="false"
                  list-type="picture-card"
                  accept="image/*"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="vehicleLicensePreview"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="
                          handlePictureCardPreview({
                            url: vehicleLicensePreview,
                          })
                        "
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        class="el-upload-list__item-delete"
                        @click="clearVehicleLicenseImage"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <div class="ocr-tips">上传行驶证主页照片自动识别信息</div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 驾驶证信息部分 -->
        <div class="form-section" v-if="drivingLicenseInfo">
          <h3 class="section-title">驾驶证信息</h3>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="准驾车型">
                <el-input
                  v-model="drivingLicenseInfo.vehicleType"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="初次领证日期">
                <el-input
                  v-model="drivingLicenseInfo.issueDate"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="有效期至">
                <el-input
                  v-model="drivingLicenseInfo.validTo"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 行驶证信息部分 -->
        <div class="form-section" v-if="vehicleLicenseInfo">
          <h3 class="section-title">行驶证信息</h3>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="车牌号码">
                <el-input
                  v-model="vehicleLicenseInfo.plateNumber"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="车辆类型">
                <el-input
                  v-model="vehicleLicenseInfo.vehicleType"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="所有人">
                <el-input
                  v-model="vehicleLicenseInfo.owner"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitForm" :loading="isSubmitting"
            >提交注册</el-button
          >
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="back">返回</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="图片预览"
      width="800px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>

    <!-- 相机对话框 -->
    <el-dialog
      :visible.sync="cameraVisible"
      title="拍摄人脸照片"
      width="600px"
      append-to-body
    >
      <div class="camera-container">
        <video id="video" autoplay></video>
        <canvas id="canvas" style="display: none"></canvas>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cameraVisible = false">取消</el-button>
        <el-button type="primary" @click="captureImage">拍照</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAuthToken,
  faceDetect,
  recognize,
  uploadIdCard,
  uploadDrivingLicence,
  uploadVehicleLicense,
} from "@/api/driver/faceRecognition";
import { addDriverUser } from "@/api/driver/driverUser";

export default {
  name: "DriverFaceRegister",
  data() {
    return {
      registerForm: {
        driverName: "",
        driverSex: "男",
        driverNation: "",
        driverBirth: "",
        driverAddress: "",
        idCard: "",
        faceToken: "",
      },
      rules: {
        driverName: [
          { required: true, message: "请输入司机姓名", trigger: "blur" },
        ],
        idCard: [
          { required: true, message: "请输入身份证号", trigger: "blur" },
          {
            pattern:
              /(^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}$)/,
            message: "请输入正确的身份证号码",
            trigger: "blur",
          },
        ],
        driverAddress: [
          { required: true, message: "请输入住址", trigger: "blur" },
        ],
      },
      uploadUrl: "", // 上传地址，实际不会使用，因为我们会手动控制上传
      isDetecting: false,
      detectionResult: null,
      dialogVisible: false,
      dialogImageUrl: "",
      cameraVisible: false,
      isSubmitting: false,
      idCardPreview: "",
      drivingLicensePreview: "",
      vehicleLicensePreview: "",
      drivingLicenseInfo: null,
      vehicleLicenseInfo: null,
      video: null,
      canvas: null,
      stream: null,
    };
  },
  methods: {
    // 人脸照片上传前处理
    handleFaceUploadBefore(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("上传图片大小不能超过 10MB!");
        return false;
      }

      // 手动上传并检测人脸
      this.detectFace(file);
      return false; // 阻止自动上传
    },

    // 人脸检测
    async detectFace(file) {
      this.isDetecting = true;
      this.detectionResult = null;

      try {
        const formData = new FormData();
        formData.append("file", file);

        const response = await faceDetect(formData);
        if (response.code === 200) {
          // 检测成功，提取faceToken
          const result = response.data;
          if (result.face_num > 0) {
            this.registerForm.faceToken = result.face_list[0].face_token;
            this.detectionResult = {
              success: true,
              message: "人脸检测成功，可以进行注册",
            };

            // 显示预览图
            const reader = new FileReader();
            reader.onload = (e) => {
              this.dialogImageUrl = e.target.result;
            };
            reader.readAsDataURL(file);
          } else {
            this.detectionResult = {
              success: false,
              message: "未检测到人脸，请重新上传",
            };
          }
        } else {
          this.detectionResult = {
            success: false,
            message: response.msg || "人脸检测失败",
          };
        }
      } catch (error) {
        this.detectionResult = {
          success: false,
          message: "人脸检测异常: " + error.message,
        };
      } finally {
        this.isDetecting = false;
      }
    },

    // 人脸照片上传成功处理
    handleFaceUploadSuccess(response) {
      // 由于我们阻止了自动上传，这个方法不会被调用
    },

    // 身份证上传成功处理
    handleIdCardUploadSuccess(response) {
      // 由于我们阻止了自动上传，这个方法不会被调用
    },

    // 驾驶证上传成功处理
    handleDrivingLicenseUploadSuccess(response) {
      // 由于我们阻止了自动上传，这个方法不会被调用
    },

    // 行驶证上传成功处理
    handleVehicleLicenseUploadSuccess(response) {
      // 由于我们阻止了自动上传，这个方法不会被调用
    },

    // 人脸照片上传失败处理
    handleFaceUploadError(error) {
      this.$message.error("上传失败，请重试");
    },

    // 身份证上传失败处理
    handleIdCardUploadError(error) {
      this.$message.error("上传失败，请重试");
    },

    // 驾驶证上传失败处理
    handleDrivingLicenseUploadError(error) {
      this.$message.error("上传失败，请重试");
    },

    // 行驶证上传失败处理
    handleVehicleLicenseUploadError(error) {
      this.$message.error("上传失败，请重试");
    },

    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 删除图片
    handleRemove(file) {
      this.dialogImageUrl = "";
      this.registerForm.faceToken = "";
      this.detectionResult = null;
    },

    // 开始相机
    startCamera() {
      this.cameraVisible = true;
      this.$nextTick(() => {
        this.initCamera();
      });
    },

    // 初始化相机
    initCamera() {
      this.video = document.getElementById("video");
      this.canvas = document.getElementById("canvas");

      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices
          .getUserMedia({ video: true })
          .then((stream) => {
            this.stream = stream;
            this.video.srcObject = stream;
            this.video.play();
          })
          .catch((err) => {
            console.error("获取摄像头失败: ", err);
            this.$message.error("获取摄像头失败，请确保已授予摄像头权限");
            this.cameraVisible = false;
          });
      } else {
        this.$message.error("您的浏览器不支持相机功能");
        this.cameraVisible = false;
      }
    },

    // 拍摄照片
    captureImage() {
      const context = this.canvas.getContext("2d");
      this.canvas.width = this.video.videoWidth;
      this.canvas.height = this.video.videoHeight;
      context.drawImage(
        this.video,
        0,
        0,
        this.canvas.width,
        this.canvas.height
      );

      // 将canvas内容转换为blob
      this.canvas.toBlob((blob) => {
        const file = new File([blob], "face_" + Date.now() + ".jpg", {
          type: "image/jpeg",
        });
        this.detectFace(file);
      }, "image/jpeg");

      // 关闭相机
      if (this.stream) {
        this.stream.getTracks().forEach((track) => track.stop());
      }
      this.cameraVisible = false;
    },

    // 身份证上传前处理
    handleIdCardUploadBefore(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }

      // 手动上传并识别身份证
      this.ocrIdCard(file);
      return false; // 阻止自动上传
    },

    // 身份证OCR识别
    async ocrIdCard(file) {
      this.$loading.show();
      try {
        const formData = new FormData();
        formData.append("file", file);

        const response = await uploadIdCard(formData);
        if (response.code === 200) {
          const idCardInfo = response.data;
          if (idCardInfo) {
            // 填充表单数据
            this.registerForm.driverName = idCardInfo.name || "";
            this.registerForm.driverSex = idCardInfo.sex || "";
            this.registerForm.driverNation = idCardInfo.nation || "";
            this.registerForm.driverBirth = idCardInfo.birth || "";
            this.registerForm.driverAddress = idCardInfo.address || "";
            this.registerForm.idCard = idCardInfo.idNumber || "";

            // 显示预览图
            const reader = new FileReader();
            reader.onload = (e) => {
              this.idCardPreview = e.target.result;
            };
            reader.readAsDataURL(file);

            this.$message.success("身份证识别成功");
          } else {
            this.$message.error("身份证识别失败，未获取到有效信息");
          }
        } else {
          this.$message.error(response.message || "身份证识别失败");
        }
      } catch (error) {
        this.$message.error("身份证识别异常: " + error.message);
      } finally {
        this.$loading.hide();
      }
    },

    // 清空身份证图片
    clearIdCardImage() {
      this.idCardPreview = "";
    },

    // 驾驶证上传前处理
    handleDrivingLicenseUploadBefore(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }

      // 手动上传并识别驾驶证
      this.ocrDrivingLicense(file);
      return false; // 阻止自动上传
    },

    // 驾驶证OCR识别
    async ocrDrivingLicense(file) {
      this.$loading.show();
      try {
        const formData = new FormData();
        formData.append("file", file);

        const response = await uploadDrivingLicence(formData);
        if (response.code === 200) {
          this.drivingLicenseInfo = response.data;
          if (this.drivingLicenseInfo) {
            // 显示预览图
            const reader = new FileReader();
            reader.onload = (e) => {
              this.drivingLicensePreview = e.target.result;
            };
            reader.readAsDataURL(file);

            this.$message.success("驾驶证识别成功");
          } else {
            this.$message.error("驾驶证识别失败，未获取到有效信息");
          }
        } else {
          this.$message.error(response.message || "驾驶证识别失败");
        }
      } catch (error) {
        this.$message.error("驾驶证识别异常: " + error.message);
      } finally {
        this.$loading.hide();
      }
    },

    // 清空驾驶证图片
    clearDrivingLicenseImage() {
      this.drivingLicensePreview = "";
      this.drivingLicenseInfo = null;
    },

    // 行驶证上传前处理
    handleVehicleLicenseUploadBefore(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件!");
        return false;
      }

      // 手动上传并识别行驶证
      this.ocrVehicleLicense(file);
      return false; // 阻止自动上传
    },

    // 行驶证OCR识别
    async ocrVehicleLicense(file) {
      this.$loading.show();
      try {
        const formData = new FormData();
        formData.append("file", file);

        const response = await uploadVehicleLicense(formData);
        if (response.code === 200) {
          this.vehicleLicenseInfo = response.data;
          if (this.vehicleLicenseInfo) {
            // 显示预览图
            const reader = new FileReader();
            reader.onload = (e) => {
              this.vehicleLicensePreview = e.target.result;
            };
            reader.readAsDataURL(file);

            this.$message.success("行驶证识别成功");
          } else {
            this.$message.error("行驶证识别失败，未获取到有效信息");
          }
        } else {
          this.$message.error(response.message || "行驶证识别失败");
        }
      } catch (error) {
        this.$message.error("行驶证识别异常: " + error.message);
      } finally {
        this.$loading.hide();
      }
    },

    // 清空行驶证图片
    clearVehicleLicenseImage() {
      this.vehicleLicensePreview = "";
      this.vehicleLicenseInfo = null;
    },

    // 提交注册
    async submitForm() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          // 检查是否已进行人脸检测
          if (!this.registerForm.faceToken) {
            this.$message.error("请先上传人脸照片并完成检测");
            return;
          }

          this.isSubmitting = true;
          try {
            // 提交司机信息
            const response = await addDriverUser(this.registerForm);
            if (response.code === 200) {
              this.$message.success("注册成功");
              this.resetForm();
            } else {
              this.$message.error(response.msg || "注册失败");
            }
          } catch (error) {
            this.$message.error("注册异常: " + error.message);
          } finally {
            this.isSubmitting = false;
          }
        }
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.registerForm.resetFields();
      this.dialogImageUrl = "";
      this.idCardPreview = "";
      this.drivingLicensePreview = "";
      this.vehicleLicensePreview = "";
      this.drivingLicenseInfo = null;
      this.vehicleLicenseInfo = null;
      this.registerForm.faceToken = "";
      this.detectionResult = null;
    },

    // 返回
    back() {
      this.$router.back();
    },
  },
  beforeDestroy() {
    // 确保关闭相机流
    if (this.stream) {
      this.stream.getTracks().forEach((track) => track.stop());
    }
  },
};
</script>

<style scoped>
.register-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.card-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
}

.card-header span {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.face-image-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.camera-button {
  margin-top: 10px;
}

.detection-status {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  background-color: #e6f7ff;
  border-radius: 4px;
  color: #1890ff;
}

.detection-result {
  margin-top: 10px;
  width: 100%;
  text-align: center;
}

.form-actions {
  display: flex;
  justify-content: center;
  padding: 20px;
  border-top: 1px solid #ebeef5;
}

.form-actions button {
  margin: 0 10px;
}

.camera-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

#video {
  max-width: 100%;
  border-radius: 8px;
}

.ocr-tips {
  text-align: center;
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}
</style>
